//
//  TSSectionListViewController.m
//  chart
//
//  Created by xu on 15/9/12.
//  Copyright (c) 2015年 xu. All rights reserved.
//

#import "TSSectionListViewController.h"
#import "TSSectionUserModel.h"
#import "RATreeView.h"
#import "RADataObject.h"
#import "TSUserViewController.h"
#import "TSMultipleCheckCell.h"
#import "TSSectionStatisticListViewController.h"
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]


@interface TSSectionListViewController () <RATreeViewDelegate, RATreeViewDataSource>

@property (strong, nonatomic) NSArray *data;
@property (strong, nonatomic) id expanded;
@property (weak, nonatomic) RATreeView *treeView;
@end

@implementation TSSectionListViewController{
    TSSectionUserModel *rootSectionModel;
    TSSectionUserModel *singleSectionModel;
    NSMutableArray *rootSectionList;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    WS(weakSelf);
    [self rightBarButtonWithTitle:nil barNorImage:[UIImage imageNamed:@"topic_follow_add"] barHltImage:nil action:^{
        [weakSelf onRightBarBarButtonClick];
    }];
    self.title = @"部门列表";
    
    RATreeView *treeView = [[RATreeView alloc] initWithFrame:CGRectMake(0, 0, currentDeviceWidth, CGRectGetHeight(self.view.bounds)-104.f)];
    
    treeView.delegate = self;
    treeView.dataSource = self;
    treeView.separatorStyle = RATreeViewCellSeparatorStyleSingleLine;
    
    [treeView reloadData];
    [treeView setBackgroundColor:UIColorFromRGB(0xF7F7F7)];
    
    self.treeView = treeView;
    [self.view addSubview:treeView];
    
    /* 加入root部门列表 */
    rootSectionModel = [[TSSectionUserModel alloc] init];
    rootSectionModel.requestParams = @{TSDictionaryKeyDefine_Id:@(1)};
    [rootSectionModel fetchWithPath:kRequestUrl_Journal_outList_pointList_section completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [weakSelf assembleRootSectionList];
        }
    } NoProgress:NO];
}

- (void)onRightBarBarButtonClick
{
    TSSectionStatisticListViewController *schedule_vc = [[TSSectionStatisticListViewController alloc] init];
    TSBaseNavigationController *nav = [[TSBaseNavigationController alloc] initWithRootViewController:schedule_vc];
    [self presentViewController:nav animated:YES completion:nil];
}

/* 组装数据 */
- (void)assembleRootSectionList
{
    
    if (rootSectionModel && rootSectionModel.sectionList) {
        RADataObject *section;
        TSSectionUserItemModel *model;
        rootSectionList = [[NSMutableArray alloc] initWithCapacity:1];
        for (int i=0; i<rootSectionModel.sectionList.count; i++) {
            model = [rootSectionModel.sectionList objectAtIndex:i];
            section = [RADataObject dataObjectWithName:model.userId Name:model.name Type:model.type.integerValue children:nil];
            [rootSectionList addObject:section];
        }
        
        if (rootSectionList.count > 0) {
            self.data = rootSectionList;
            [self.treeView reloadData];
        }
    }
}

- (void)getSectionById:(NSString *)sectionId
{
    WS(weakSelf);
    singleSectionModel = [[TSSectionUserModel alloc] init];
    singleSectionModel.requestParams = @{TSDictionaryKeyDefine_Id:sectionId};
    [singleSectionModel fetchWithPath:kRequestUrl_Journal_outList_pointList_section completionHandler:^(BOOL isSucceeded, NSError *error) {
        if (!weakSelf) {
            return;
        }
        
        if (isSucceeded) {
            [weakSelf assembleSingleSectionList:sectionId];
        }
    } NoProgress:YES];
}

/* 将请求回来的子部门加入到rootSectionList中 */
- (void)assembleSingleSectionList:(NSString *)sectionId
{
    if (rootSectionList && singleSectionModel) {
        NSArray *new_children = [self createSectionObjects:singleSectionModel.sectionList];
        
        [self appendChildrenToOwnSuperObject:sectionId InArray:rootSectionList AppendChildren:new_children];
        
        [self.treeView reloadData];
    }
}

/* 查询下属部门回来后构造成RADataObject对象 */
- (NSArray *)createSectionObjects:(NSArray *)array
{
    NSMutableArray *objs_arry = [[NSMutableArray alloc] initWithCapacity:1];
    if (array) {
        for (TSSectionUserItemModel *model in array) {
            RADataObject *obj = [[RADataObject alloc] initWithId:model.userId Name:model.name Type:model.type.integerValue children:nil];
            [objs_arry addObject:obj];
        }
        
        return objs_arry;
    }
    
    return nil;
}

- (void)appendChildrenToOwnSuperObject:(NSString *)sectionId InArray:(NSArray *)array AppendChildren:(NSArray *)children
{
    RADataObject *model;
    if (array) {
        for (int i=0; i<array.count; i++) {
            model = [array objectAtIndex:i];
            
            if ([model.sectionId isEqualToString:sectionId]) {
                model.children = children;
                
                if ([self.expanded isEqual:model]) {
                    [self.treeView collapseRowForItem:model];
                }else{
                    self.expanded = model;
                }
                
                break;
            }
            
            if (model.children) {
                [self appendChildrenToOwnSuperObject:sectionId InArray:model.children AppendChildren:children];
            }
        }
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

#pragma mark TreeView Delegate methods
- (CGFloat)treeView:(RATreeView *)treeView heightForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return 47;
}

- (NSInteger)treeView:(RATreeView *)treeView indentationLevelForRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return 3 * treeNodeInfo.treeDepthLevel;
}

- (BOOL)treeView:(RATreeView *)treeView shouldExpandItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    return YES;
}

- (BOOL)treeView:(RATreeView *)treeView shouldItemBeExpandedAfterDataReload:(id)item treeDepthLevel:(NSInteger)treeDepthLevel
{
    if ([item isEqual:self.expanded]) {
        return YES;
    }
    return NO;
}

- (void)treeView:(RATreeView *)treeView willDisplayCell:(UITableViewCell *)cell forItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    if (treeNodeInfo.treeDepthLevel == 0) {
        cell.backgroundColor = UIColorFromRGB(0xF7F7F7);
    } else if (treeNodeInfo.treeDepthLevel == 1) {
        cell.backgroundColor = UIColorFromRGB(0xD1EEFC);
    } else if (treeNodeInfo.treeDepthLevel == 2) {
        cell.backgroundColor = UIColorFromRGB(0xE0F8D8);
    }
}

#pragma mark TreeView Data Source

- (UITableViewCell *)treeView:(RATreeView *)treeView cellForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"cell"];
    cell.textLabel.text = ((RADataObject *)item).name;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (treeNodeInfo.treeDepthLevel == 0) {
        cell.detailTextLabel.textColor = [UIColor blackColor];
    }
    return cell;
}

- (NSInteger)treeView:(RATreeView *)treeView numberOfChildrenOfItem:(id)item
{
    if (item == nil) {
        return [self.data count];
    }
    RADataObject *data = item;
    return [data.children count];
}

- (id)treeView:(RATreeView *)treeView child:(NSInteger)index ofItem:(id)item
{
    RADataObject *data = item;
    if (item == nil) {
        return [self.data objectAtIndex:index];
    }
    return [data.children objectAtIndex:index];
}

- (void)treeView:(RATreeView *)treeView didSelectRowForItem:(id)item treeNodeInfo:(RATreeNodeInfo *)treeNodeInfo
{
    RADataObject *obj = treeNodeInfo.item;
    
    if (obj.type == TSSectionUserItemModel_Type_Section) {
        if (obj.type == TSSectionUserItemModel_Type_Section) {
            if ([self.expanded isEqual:obj]) {
                
            }else{
                if(!obj.children){
                    [self getSectionById:obj.sectionId];
                }
            }
        }
        
        
    }
    else if (obj.type == TSSectionUserItemModel_Type_User){ // 跳转个人日程页面
        TSUserViewController *user_vc = [[TSUserViewController alloc] init];
        user_vc.userId = obj.sectionId;
        
        TSBaseNavigationController *nav_vc = [[TSBaseNavigationController alloc] initWithRootViewController:user_vc];
        
        [self.navigationController presentViewController:nav_vc animated:YES completion:nil];
    }
}




@end
